import { Button, Card, Form, Input, InputNumber, message, Upload } from 'antd'
import React, { useEffect, useState } from 'react'
import { createApi, selectOne } from '../../../service/products'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'

function Edit(props) {

    const [currentData, setCurrentData] = useState({})
    const [loading, setLoading] = useState(false)
    const [imageUrl, setImageUrl] = useState('')
    const [form] = Form.useForm()

    useEffect(() => {
        selectOne(props.match.params.id).then(res => {
            setCurrentData(res)
            form.setFieldsValue(res)
        }).catch(error => {
            message.info(error.message)
        })
    }, [])

    const beforeUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp';
        if (!isJpgOrPng) {
            message.error('You can only upload JPG/PNG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
    };

    const handleChange = (info) => {
        console.log('handleChange', info)

        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            // getBase64(info.file.originFileObj, (url) => {
            setLoading(false);
            setImageUrl(info.file.response.url);
            // });
        }

        if (info.file.status === 'error') {
            message.info(info.file.error.message)
            setLoading(false)
            setImageUrl(undefined)
        }
    };

    const handleSubmit = e => {
        createApi(e).then(res => {
            props.history.push('/admin/products')
        }).catch(error => {
            message.info(error.message)
        })
    }

    return (
        <Card title="商品编辑">
            <Form
                form={form}
                labelCol={{
                    span: 6,
                }}
                wrapperCol={{
                    span: 18,
                }}
                onFinish={e => handleSubmit(e)}>
                <Form.Item label="头像" name='avatar'>
                    <Upload
                        name="avatar"
                        listType="picture-card"
                        className="avatar-uploader"
                        showUploadList={false}
                        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                        beforeUpload={beforeUpload}
                        onChange={handleChange}
                    >
                        {imageUrl ? (
                            <img
                                src={imageUrl}
                                alt="avatar"
                                style={{
                                    width: '100%',
                                }}
                            />
                        ) : (
                            <div>
                                {loading ? <LoadingOutlined /> : <PlusOutlined />}
                                <div
                                    style={{
                                        marginTop: 8,
                                    }}
                                >
                                    Upload
                                </div>
                            </div>
                        )}
                    </Upload>
                </Form.Item>
                <Form.Item label="姓名" name='name'
                    rules={[
                        {
                            required: true,
                            message: '请输入尊姓大名!',
                        },
                    ]} >
                    <Input placeholder="请输入尊姓大名!" ></Input>
                </Form.Item>
                <Form.Item label="年龄" name='age'
                    rules={[
                        {
                            required: true,
                            message: '请输入年龄！'
                        }, {
                            validator(rule, value) {
                                if (value <= 0) {
                                    return Promise.reject(new Error('年龄不得小于0'));
                                }
                                if (value > 150) {
                                    return Promise.reject(new Error('年龄不得大于150'));
                                }
                                return Promise.resolve(value)
                            }
                        }
                    ]} >
                    <InputNumber placeholder='请输入年龄！' style={{ width: '100%' }} />
                </Form.Item>
                <Form.Item label="住址" name='address'
                    rules={[
                        {
                            required: true,
                            message: '请输入府邸地址!',
                        },
                    ]} >
                    <Input placeholder="请输入府邸地址!" ></Input>
                </Form.Item>
                <Form.Item wrapperCol={{ offset: 6, span: 18 }}>
                    <Button type='primary' htmlType='submit'>保存</Button>
                </Form.Item>
            </Form>
        </Card>
    )
}

export default Edit